package com.nyist.controller;

import com.nyist.lb.LoadBalancer;
import com.nyist.pojo.User;
import com.nyist.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Resource
    LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    //private static String url="http://localhost";
    private static String url="http://CLOUD-PROVIDER";

    @GetMapping(value = "/consumer/test/{name}")
    public CommonResult test(@PathVariable("name") String name) {
        System.out.println("进入消费者：进行消费");
        return restTemplate.getForObject(url+"/provider/hello/"+name,CommonResult.class);
    }

    @GetMapping(value = "/consumer/lb")
    public String getloadBalancerlb(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER");
        if(instanceList == null || instanceList.size()<=0){
            return null;
        }
        ServiceInstance instances = loadBalancer.instances(instanceList);
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri+"/provider/loadbalancer/lb/",String.class);
    }


    @GetMapping(value = "/consumer/zipkin")
    public String orderZipkin(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER");
        if(instanceList == null || instanceList.size()<=0){
            return null;
        }
        ServiceInstance instances = loadBalancer.instances(instanceList);
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri+"/provider/zipkin",String.class);
    }
}
